package bintree.heap.leetcode;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class 最小的K个数 {
    public int[] getLeastNumbers(int[] arr, int k) {
//        Arrays.sort(arr);
//        int[]  arr1 = new int[k];
//        for (int i = 0; i < k; i++) {
//            arr1[i] = arr[i];
//        }
//        return arr1;
        int[]  arr1 = new int[k];
        if (arr.length==0 || k==0){
            return arr1;
        }
    Queue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });
        for (int i = 0; i < arr.length; i++) {
            if (pq.size()<k){
                pq.offer(arr[i]);
            }else {
                int a = pq.peek();
                if (arr[i]<a){
                    pq.poll();
                    pq.offer(arr[i]);
                }
            }
        }
        int i = 0;
        while (!pq.isEmpty()){
            arr1[i++] = pq.poll();

        }
        return arr1;
}
    }

